package com.bilibili.common;

import com.bilibili.enumeration.Gender;
import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;

@JsonComponent
public class JsonConverter {

    public static class GenderSerializer extends JsonSerializer<Gender> {

        @Override
        public void serialize(Gender gender, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            jsonGenerator.writeObject(gender.name());
            jsonGenerator.writeNumberField("genderCode", gender.getCode());
            jsonGenerator.writeStringField("genderCode", gender.getName());
        }
    }

    public static class GenderDeserializer extends JsonDeserializer<Gender>{

        @Override
        public Gender deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JacksonException {
            int code = jsonParser.getIntValue();
            return BaseEnum.getByCode(code, Gender.class);
        }
    }



}
